package com.h.forum.controller;

import com.h.forum.common.constant.Constants;
import com.h.forum.common.enums.ResultCode;
import com.h.forum.exception.ApplicationException;
import com.h.forum.pojo.model.Board;
import com.h.forum.pojo.response.AppResult;
import com.h.forum.pojo.response.BoardInfoResponse;
import com.h.forum.services.IBoardService;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/board")
public class BoardController {

    // 从配置文件中读取值 ，如果没有配置，默认值为9
    @Value("${h-forum.index.board-num:9}")
    private Integer indexBoardNum;

    @Resource(name = "boardServiceImpl")
    private IBoardService boardService;

    /**
     * 返回板块列表
     * @return
     */
    @GetMapping("/topList")
    public AppResult<BoardInfoResponse> topList() {
        log.info("首页版块个数为：" + indexBoardNum);
        // 调用Service 获取信息
        BoardInfoResponse response = boardService.selectByNum(indexBoardNum);
        // 判断
        if (response == null) {
            response = new BoardInfoResponse();
        }
        return AppResult.success(response);
    }

    @GetMapping("/getById")
    public AppResult<Board> getById(@RequestParam(value = "id") @NotNull Long id) {
        // 调用Service
        Board board = boardService.selectById(id);

        // 对查询结果进行校验
        if (board == null || board.getDeleteState().equals(Constants.IS_DELETE_STATE)) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        return AppResult.success(board);
    }
}
